import axios from 'axios';
import { ElMessage } from 'element-plus';

const http = axios.create({
  baseURL: 'http://112.126.93.146:8000',
  timeout: 10000,
});
http.interceptors.request.use(
   (config: any) => {
    // 从localStorage获取tokens
    const token = localStorage.getItem("token") ?? ""
    if (token && config.headers) {
      config.headers.Authorization = "Bearer"+" "+token;
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
);

http.interceptors.response.use( 
  (response: any) => {
    // 统一处理响应
    return response;
  },
  (error: any) => {
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      // 可以在这里跳转到登录页
    } else {
      ElMessage.error(error.response?.data?.message || '请求失败')
    }
    return Promise.reject(error)
  }
);

export   {http};